package zsh.controller;

import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import zsh.config.UploadProperty;
import zsh.core.Result;
import zsh.domain.User;
import zsh.service.impl.UserServiceImpl;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

@RestController
@AllArgsConstructor
public class UserController {
    private final UserServiceImpl userServiceImpl;
    private final UploadProperty uploadProperty;
    //注册
//    @PostMapping("/sign")
//    public Result sign(@RequestBody User user){
//
//        return Result.success(userServiceImpl.addUser(user));
//    }

    @PostMapping("/sign")
    public Result sign(MultipartFile file, User user) {
        //用户上传了头像
        if (!file.isEmpty()) {
            String originalFilename = file.getOriginalFilename();
            if (originalFilename == null || !originalFilename.contains(".")) {
                return Result.error(500, "文件名无效，必须包含扩展名");
            }

            String suffix = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase();
            List<String> supportedSuffix = Arrays.asList("jpg", "jpeg", "png", "gif");

            if (!supportedSuffix.contains(suffix.substring(1))) { // 去掉点号进行比较
                return Result.error(500, "格式仅支持jpg,jpeg,png,gif");
            }
            //最终文件名
            String filename = "avatar/"+System.currentTimeMillis()+"-"+originalFilename;
            try {
                file.transferTo(new File(uploadProperty.getLocalPath() + filename));
                user.setAvatar(filename);
            } catch (IOException e) {
                return Result.error(500, "头像上传失败，请联系管理员");
            }
        }
        userServiceImpl.addUser(user);
        return Result.success(user);
    }



    //登陆
    @PostMapping("/login")
    public Result<User> login(String username, String password, HttpSession session, HttpServletRequest request) {
        User user = userServiceImpl.login(username,password);
        //登陆成功保存session
        session.setAttribute("LoginUser",user);
        return Result.success(user);
    }
}
